/*
 * Copyright 2013 Pavel Stastny <pavel.stastny at gmail.com>.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.aplikator.client.local.widgets;

import com.github.gwtbootstrap.client.ui.FluidRow;
import com.github.gwtbootstrap.client.ui.Form;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
import org.aplikator.client.shared.data.Record;
import org.aplikator.client.shared.descriptor.FormDTO;
import org.aplikator.client.shared.descriptor.PropertyDTO;
import org.aplikator.client.shared.descriptor.RenderWidgetAware;
import org.aplikator.client.shared.descriptor.WidgetDTO;

import java.io.Serializable;

/**
 * Represents abstract FormWidget 
 * @author Pavel Stastny <pavel.stastny at gmail.com>
 */
public abstract class AbstractFormContainerWidget extends Composite implements  HasFields {

    /**
     * Form widget initialization
     * @param descriptor FormDTO descriptor
     * @param wrapper Form widget
     */
    protected void initializeForm(FormDTO descriptor, Form wrapper) {
        FluidRow layoutRoot = new FluidRow();
        WidgetDTO layout = descriptor.getLayout();
        Widget form = ((RenderWidgetAware)layout).getWidget(this);
        layoutRoot.add(form);
        wrapper.add(layoutRoot);
        initWidget(wrapper);
    }

    public abstract Record getPopulateRecord();

    @SuppressWarnings("unchecked")
    public void populateFormWithSimpleData(boolean setDirty) {
        setDirty(setDirty);
        for (DataField field : getDataFields()) {
            PropertyDTO prop = field.getProperty();
            Serializable val = (Serializable) prop.getValue(getPopulateRecord());
            field.setValue(val);
            field.setDirty(setDirty);
        }
    }
}
